﻿package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.activity.RechargeActivity.MyPopListViewClick;
import com.kuanter.kuanterauto.activity.RechargeActivity.SelecterGradePopupWindow;
import com.kuanter.kuanterauto.activity.RechargeActivity.SelecterGradePopupWindow.PopInsuranceAdapter;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.CardInfo;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.kuanter.kuanterauto.utils.StringUtils;
import com.kuanter.kuanterauto.utils.Utility;
import com.umeng.analytics.MobclickAgent;
import com.weibo.sdk.android.api.FavoritesAPI;
/**
 * 激活卡片（未注册宽途用户）类
 * @author kuanter
 *
 */
public class ActivateCardNextActivity extends WuyangBaseActivity implements OnClickListener{
	private static final int CHOOSE_CAR_NUMBER = 265;
	private static final int CHOOSE_CAR_TYPE = 267;
	private Intent intent = new Intent();
	
	private String cardNumber;
	
	private String mobileNumber;
	private DataLoader dataLoader;
	/**
	 * 填写个人信息及车辆信息的激活卡片handler
	 */
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
							com.alibaba.fastjson.JSONObject jsonObjectResult1 = JSON.parseObject(result);
							CardInfo cardInfo = jsonObjectResult1.getObject("cardInfo", CardInfo.class);
							Intent intent = new Intent(ActivateCardNextActivity.this,ActivateCardSuccessedActivity.class);
							if(null != cardInfo.getCardNumber()&& !"".equals(cardInfo.getCardNumber())){
								intent.putExtra("cardNumber", cardInfo.getCardNumber());
							}
							if(null != cardInfo.getPointBalance()&& !"".equals(cardInfo.getPointBalance())){
								intent.putExtra("pointBalance", cardInfo.getPointBalance());
							}else {
								intent.putExtra("pointBalance","暂无");
							}
							if(null != cardInfo.getExpireTime()&& !"".equals(cardInfo.getExpireTime())){
								intent.putExtra("expireTime", cardInfo.getExpireTime());
							}else {
								intent.putExtra("expireTime", "暂无");
							}
							startActivity(intent);
							finishProgress();
						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
							showToast("失败");
						}
					} catch (JSONException e) {
						finishProgress();
						e.printStackTrace();
					}
				} else {
					finishProgress();
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	private View choose_car_number;
	private View choose_car_type;
	private TextView license_plate_nubmer_tv;
	private TextView car_model_tv;
	private EditText user_name_et;
	private String user_name;
	private EditText email_et;
	private String email = "";
	private String pp="";
	private String xh="";
	private String license_plate_nubmer ="";
	private EditText user_password_et;
	private EditText user_password_confirm_et;
	private String user_password;
	private String user_password_confirm;
	private ArrayList<NameValuePair> params;
	private SelecterGradePopupWindow menuWindow;
	private ArrayList<String> sexs = new ArrayList<String>();
	private TextView optionSex;
	private String sex = "";
	private TextView famaleOrMale;
	
	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activate_card_next);
		super.onCreate(savedInstanceState);
		this.setHeaderControlViewText();
		this.initBodyControlView();
		this.setBodyControlViewText();
		this.registerListener();
		//获取上个界面传来的intent
		Intent getIntent = getIntent();
		cardNumber = getIntent.getStringExtra("cardNumber");
		mobileNumber = getIntent.getStringExtra("mobileNumber");
		dataLoader = new DataLoader(this);
		ProApplication.getInstance().getActivityList().add(this);
	}
	@Override
	protected void onDestroy() {
		 ProApplication.getInstance().getActivityList().remove(this);
		super.onDestroy();
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.header_left:
			this.finish();
			break;
		case R.id.header_right:
			//激活卡片
			this.getControlViewText();
				//封装此处数据
				if(null == user_name||"".equals(user_name)){
					showToast("您没填新用户姓名哦");
				}else if(isE(user_name)){
					showToast("用户姓名要填中文哦");
				}else if(null == user_password|| "".equals(user_password)){
					showToast("您没填新用户密码哦");
				}else if(user_password.length() != 6){
					showToast("密码长度要为六位哦");
				}else if(null == user_password_confirm || "".equals(user_password_confirm)){
					showToast("您还没确认密码哦");
				}else if(user_password_confirm.length() != 6){
					showToast("密码长度要为六位哦");
				}else if(!user_password.equals(user_password_confirm)){
					showToast("两次填写的新用户密码不一样哦");
				}/*else if(null != email || !"".equals(email)){
					StringUtils.isEmail(email);
					showToast("您没填邮箱号哦");
				}*//*else if(false == StringUtils.isEmail(email)){
					showToast("您输入的不是邮箱号哦");
				}else if(null == license_plate_nubmer || "".equals(license_plate_nubmer)){
					showToast("您没选车牌号哦");
				}else if(null == pp || "".equals(pp)){
					showToast("您没选车型哦");
				}else if(null == xh || "".equals(xh)){
					showToast("您没选型号哦");
				}*/else {
					//上传该数据给服务器激活
					params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("cardNumber",cardNumber));
					params.add(new BasicNameValuePair("mobileNumber",mobileNumber));
					params.add(new BasicNameValuePair("userRealName",user_name));
					params.add(new BasicNameValuePair("userPassword",user_password));
					if(email.equals("")){
						/*if(!license_plate_nubmer.equals("")){
							params.add(new BasicNameValuePair("licensePlateNumber",license_plate_nubmer));
						}*/
						if(!sex.equals("")){
							params.add(new BasicNameValuePair("gender",sex));
						}
						if(!pp.equals("")){
							if(license_plate_nubmer.equals("")){
								showToast("车型号已选，请填写车牌号");
								break;
							}else if(!license_plate_nubmer.equals("")){
								params.add(new BasicNameValuePair("licensePlateNumber",license_plate_nubmer));
							}
							params.add(new BasicNameValuePair("vehicleBrand",pp));
						}else if(pp.equals("")){
							params.add(new BasicNameValuePair("vehicleBrand",pp));
						}
						if(!xh.equals("")){
							params.add(new BasicNameValuePair("vehicleModels",xh));
						}else if(xh.equals("")){
							params.add(new BasicNameValuePair("vehicleModels",xh));
						}
						
						dataLoader.DisplayData(MainConstants.HOST_test+HttpConfigAPI.ACTIVATE_CARD, params, handler, "",false) ;
						showProgress("正在加载数据...");
					}else if(!email.equals("")){
						if(StringUtils.isEmail(email)){
							params.add(new BasicNameValuePair("userEmail",email));
							/*if(!license_plate_nubmer.equals("")){
								params.add(new BasicNameValuePair("licensePlateNumber",license_plate_nubmer));
							}*/
							if(!sex.equals("")){
								params.add(new BasicNameValuePair("gender",sex));
							}
							if(!pp.equals("")){
								if(license_plate_nubmer.equals("")){
									showToast("车型号已选，请填写车牌号");
									break;
								}else if(!license_plate_nubmer.equals("")){
									params.add(new BasicNameValuePair("licensePlateNumber",license_plate_nubmer));
								}
								params.add(new BasicNameValuePair("vehicleBrand",pp));
							}else if(pp.equals("")){
								params.add(new BasicNameValuePair("vehicleBrand",pp));
							}
							if(!xh.equals("")){
								params.add(new BasicNameValuePair("vehicleModels",xh));
							}else if(xh.equals("")){
								params.add(new BasicNameValuePair("vehicleModels",xh));
							}
							
							dataLoader.DisplayData(MainConstants.HOST_test+HttpConfigAPI.ACTIVATE_CARD, params, handler, "",false) ;
							showProgress("正在加载数据...");
							
						}else if(!StringUtils.isEmail(email)){
							showToast("请填写正确的邮箱");
						}
					}
						/*params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("cardNumber",cardNumber));
						params.add(new BasicNameValuePair("mobileNumber",mobileNumber));
						params.add(new BasicNameValuePair("userRealName",user_name));
						params.add(new BasicNameValuePair("gender",sex));
						params.add(new BasicNameValuePair("userPassword",user_password));
						params.add(new BasicNameValuePair("userEmail",email));
						params.add(new BasicNameValuePair("licensePlateNumber",license_plate_nubmer));
						params.add(new BasicNameValuePair("vehicleBrand",pp));
						params.add(new BasicNameValuePair("vehicleModels",xh));
						dataLoader.DisplayData(MainConstants.HOST_test+HttpConfigAPI.ACTIVATE_CARD, params, handler, "",false) ;
						showProgress("正在加载数据...");*/
					
				}
				break;
		case R.id.choose_car_number:
			intent.setClass(this, LincensePlateNumberActivity.class);
			startActivityForResult(intent, CHOOSE_CAR_NUMBER);
			break;
		case R.id.choose_car_type:
			intent.setClass(this, XgcxActivity.class);
			startActivityForResult(intent, CHOOSE_CAR_TYPE);
			break;
		default:
			break;
		}
	}
	//optionSex
	public void optionSex(View v){
//		Toast.makeText(this, "++", 0).show();
		
		menuWindow.showAtLocation(this.findViewById(R.id.temp9), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case CHOOSE_CAR_NUMBER:
			if(null != data){
				String provice = data.getStringExtra("province");
				String car_number = data.getStringExtra("car_number");
//				license_plate_nubmer = provice+"  "+car_number;
				license_plate_nubmer = provice + car_number;
				license_plate_nubmer_tv.setText(license_plate_nubmer);
			}
			break;
		case CHOOSE_CAR_TYPE:
			if(null != data){
				pp = data.getStringExtra("pp");
				xh = data.getStringExtra("xh");
				car_model_tv.setText(pp+"  "+xh);
			}
			break;
		default:
			break;
		}
	}
	@Override
	protected void setHeaderControlViewText() {
		// TODO Auto-generated method stub
		super.setHeaderTitleText(headerTitle, "卡片激活");
		super.setHeaderLeftText(headerLeft, "返回");
		super.setHeaderRightText(headerRight, "激活");
	}
	@Override
	protected void initBodyControlView() {
		famaleOrMale = (TextView)findViewById(R.id.famaleOrMale);
		choose_car_number = (View)this.findViewById(R.id.choose_car_number);
		choose_car_number.setBackgroundResource(R.drawable.item_middle_selector);
		choose_car_type =  (View)this.findViewById(R.id.choose_car_type);
		choose_car_type.setBackgroundResource(R.drawable.item_bottom_selector);
		license_plate_nubmer_tv = (TextView)this.findViewById(R.id.license_plate_nubmer_tv);
		car_model_tv = (TextView)this.findViewById(R.id.car_model_tv);
		user_name_et = (EditText)this.findViewById(R.id.user_name_et);
		sexs.add("男");
		sexs.add("女");
		menuWindow = new SelecterGradePopupWindow(this, new MyPopListViewClick(),sexs);
		optionSex = (TextView)findViewById(R.id.optionSex);
		email_et = (EditText)this.findViewById(R.id.email_et);
		user_password_et = (EditText)this.findViewById(R.id.user_password_et);
		//设置数字密码输入
		user_password_et.setTransformationMethod(PasswordTransformationMethod.getInstance());
		user_password_et.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
		user_password_et.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
		
		user_password_confirm_et = (EditText)this.findViewById(R.id.user_password_confirm_et);
		user_password_confirm_et.setTransformationMethod(PasswordTransformationMethod.getInstance());
		user_password_confirm_et.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
		user_password_confirm_et.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
	}
	@Override
	protected void setBodyControlViewText() {
		// TODO Auto-generated method stub
		
	}
	@Override
	protected void registerListener() {
		// TODO Auto-generated method stub
		//btn rigester listener
		super.headerLeft.setOnClickListener(this);
		super.headerRight.setOnClickListener(this);
		choose_car_number.setOnClickListener(this);
		choose_car_type.setOnClickListener(this);
	}
	@Override
	protected void getControlViewText() {
		user_name = user_name_et.getText().toString();
		email = email_et.getText().toString();
		user_password = user_password_et.getText().toString();
		user_password_confirm = user_password_confirm_et.getText().toString();
		sex = optionSex.getText().toString();
		//0空1男2女
		if("女".equals(sex)){
			sex = "2";
		}else if("男".equals(sex) || "请选择".equals(sex)){
			sex = "1";
		}/*else 
			sex = "0";*/
	}

	public class MyPopListViewClick implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
				String sex = sexs.get(position);
				optionSex.setText(sex);
				if(optionSex.getText().toString().trim().equals("男") || optionSex.getText().toString().trim().equals("请选择")){
					famaleOrMale.setText("先生");
				}else {
					famaleOrMale.setText("女士");
				}
				menuWindow.dismiss();
		}

	}
	/**
	 * 自定义弹出框类
	 * @author kuanter
	 *
	 */
	public class SelecterGradePopupWindow extends PopupWindow {


		private TextView btn_cancel;
		private View mMenuView;
		
		ListView insuranceview;
		LayoutInflater inflater;
		
		PopInsuranceAdapter adapter;
		
		List<String> ci_pop;

		public SelecterGradePopupWindow(Activity context,OnItemClickListener itemsOnClick,List<String> ci_pop) {
			super(context);
			this.ci_pop = ci_pop;
			
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mMenuView = inflater.inflate(R.layout.alert_dialog, null);
			btn_cancel = (TextView) mMenuView.findViewById(R.id.btn_cancel);
			//取消按钮
			btn_cancel.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					//销毁弹出框
					dismiss();
				}
			});
			
			insuranceview = (ListView) mMenuView.findViewById(R.id.insuranceview);
			insuranceview.setOnItemClickListener(itemsOnClick);
			
			adapter = new PopInsuranceAdapter();
			insuranceview.setAdapter(adapter);
			Utility.setListViewHeightBasedOnChildren(insuranceview);
			
			//设置SelectPicPopupWindow的View
			this.setContentView(mMenuView);
			//设置SelectPicPopupWindow弹出窗体的宽
			this.setWidth(LayoutParams.FILL_PARENT);
			//设置SelectPicPopupWindow弹出窗体的高
			this.setHeight(LayoutParams.WRAP_CONTENT);
			//设置SelectPicPopupWindow弹出窗体可点击
			this.setFocusable(true);
			//设置SelectPicPopupWindow弹出窗体动画效果
			this.setAnimationStyle(R.style.AnimBottom);
			//实例化一个ColorDrawable颜色为半透明
			ColorDrawable dw = new ColorDrawable(0xb0000000);
			//设置SelectPicPopupWindow弹出窗体的背景
			this.setBackgroundDrawable(dw);
			//mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
			mMenuView.setOnTouchListener(new OnTouchListener() {
				
				public boolean onTouch(View v, MotionEvent event) {
					
					int height = mMenuView.findViewById(R.id.pop_layout).getTop();
					int y=(int) event.getY();
					if(event.getAction()==MotionEvent.ACTION_UP){
						if(y<height){
							dismiss();
						}
					}				
					return true;
				}
			});

		}
		/**
		 * 车险选择数据
		 * @author kuanter
		 *
		 */
		class PopInsuranceAdapter extends BaseAdapter {
			@Override
			public int getCount() {
				return ci_pop == null ? 0 : ci_pop.size();
			}

			@Override
			public Object getItem(int arg0) {
				return ci_pop.get(arg0);
			}

			@Override
			public long getItemId(int arg0) {
				return arg0;
			}

			@Override
			public View getView(int position, View view, ViewGroup parent) {
				if(view == null) {
					view = inflater.inflate(R.layout.pop_insurance_item, null);
				}
				TextView item_insurance = (TextView) view.findViewById(R.id.item_insurance);
				item_insurance.setText(ci_pop.get(position));
				return view;
			}
			
		}

	}
}	
